package com.qujia.station.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qujia.common.constant.Constants;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.LocalDateUtils;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.coupon.service.ICouponUserService;
import com.qujia.station.domain.AppUserSuperDetail;
import com.qujia.station.domain.PayOrder;
import com.qujia.station.domain.PayWay;
import com.qujia.station.domain.SuperPayOrder;
import com.qujia.station.domain.vo.SuperPayOrderVO;
import com.qujia.station.mapper.SuperPayOrderMapper;
import com.qujia.station.service.IAppUserSuperDetailService;
import com.qujia.station.service.IPayOrderService;
import com.qujia.station.service.IPayWayService;
import com.qujia.station.service.ISuperPayOrderService;
import com.qujia.system.domain.SysRespon;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @date 2023/12/12
 */
@Service
public class SuperPayOrderServiceImpl extends ServiceImpl<SuperPayOrderMapper, SuperPayOrder> implements ISuperPayOrderService {

    private static final Logger log = LoggerFactory.getLogger(SuperPayOrderServiceImpl.class);

    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private IPayWayService payWayService;
    @Autowired
    private ICouponUserService couponUserService;
    @Autowired
    private IAppUserSuperDetailService appUserSuperDetailService;

    @Override
    public List<SuperPayOrderVO> queryList(SuperPayOrderVO superPayOrderVO) {
        LoginUser user = SecurityUtils.getLoginUser();
        SysUser sysUser = user.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO,sysUser.getUserLevel())) {
            // 油企
            superPayOrderVO.setEnterpriseId(Math.toIntExact(sysUser.getEnterpriseId()));
        }else if(StringUtils.equals(UserConstants.LEVEL_THREE,sysUser.getUserLevel())){
            // 油站
            superPayOrderVO.setEnterpriseId(Math.toIntExact(sysUser.getEnterpriseId()));
        }
        return baseMapper.queryVOList(superPayOrderVO);
    }

    @Override
    public AjaxResult export(SuperPayOrderVO superPayOrderVO) {
        List<SuperPayOrderVO> orderVOS = queryList(superPayOrderVO);
        ExcelUtil<SuperPayOrderVO> excelUtil = new ExcelUtil<>(SuperPayOrderVO.class);
        return excelUtil.exportExcel(orderVOS,"detail");
    }

    @Override
    @Transactional
    public void refund(Integer id) {
        SuperPayOrder payOrder = getById(id);
        if (payOrder == null) {
            throw new CustomException("订单不存在");
        }
        if (!StringUtils.equals("1",payOrder.getStatus())) {
            throw new CustomException("订单已退款");
        }
        if (payOrder.getPayWayId() == null) {
            throw new CustomException("支付渠道未找到");
        }
        PayWay payWay = payWayService.selectPayWayById(Long.valueOf(payOrder.getPayWayId()));
        if (payWay == null) {
            throw new CustomException("支付渠道未找到");
        }
        rollbackSuperDetail(payOrder);
        couponUserService.recoveryUserCoupon(payOrder.getMobilePhone(), 7, Long.valueOf(payOrder.getSuperPayId()),Constants.COUPON_USER_BIZ_TYPE_SUPER_USER,false);
        doRefund(payOrder, com.qujia.common.utils.StringUtils.generateOrdNo(),payWay);
    }

    private void rollbackSuperDetail(SuperPayOrder order){
        if (order.getCycle() == null) {
            return;
        }
        AppUserSuperDetail form = new AppUserSuperDetail();
        form.setUserId(Long.valueOf(order.getAppUserId()));
        form.setEnterpriseId(Long.valueOf(order.getEnterpriseId()));
        List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailService.selectAppUserSuperDetailList(form);
        if (appUserSuperDetails.isEmpty()) {
            return;
        }
        Date now = new Date();
        AppUserSuperDetail superDetail = appUserSuperDetails.get(0);
        Date endDate = superDetail.getEndDate();
//        Date beginDate = superDetail.getBeginDate();
//        if (endDate.before(now) || endDate.before(beginDate)) {
//            // 到期时间在现在之前，或到期时间在开始之前，跳过
//            return;
//        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(endDate);
        cal.add(Calendar.DATE, -Math.toIntExact(order.getCycle()));
        Date newEndDate = cal.getTime();
        AppUserSuperDetail ud = new AppUserSuperDetail();
        ud.setSuperDetailId(superDetail.getSuperDetailId());
        ud.setEndDate(newEndDate);
        if (newEndDate.after(now) || newEndDate.after(superDetail.getBeginDate())) {
            // 到期时间在现在之后，或新的结束时间在开始之后，查找上最后一次开通记录
            LambdaQueryWrapper<SuperPayOrder> qw = Wrappers.lambdaQuery(SuperPayOrder.class);
            qw.eq(SuperPayOrder::getAppUserId,order.getAppUserId())
                    .eq(SuperPayOrder::getEnterpriseId,order.getEnterpriseId())
                    .eq(SuperPayOrder::getStatus,"1")
                    .eq(SuperPayOrder::getMobilePhone,order.getMobilePhone())
                    .ne(SuperPayOrder::getSuperPayId,order.getSuperPayId())
                    .orderByDesc(SuperPayOrder::getSuperPayId)
                    .last("limit 1");
            SuperPayOrder lastPay = getOne(qw);
            if (lastPay != null) {
                ud.setSuperId(Long.valueOf(lastPay.getSuperId()));
            }
        }
        appUserSuperDetailService.updateAppUserSuperDetail(ud);

    }

    private void doRefund(SuperPayOrder order,String refundOrderNo, PayWay payWay){
        SysRespon sysRespon;
        String thirdOrderNo= null;
        String thirdPayNo = null;
        String payType = payWay.getPayType();
        switch (payType){
            case "1":  //随行付
                sysRespon = sxfRefund(order,refundOrderNo, payWay);
                if (sysRespon != null) {
                    if (sysRespon.getData() != null) {
                        HashMap<String, Object> data = (HashMap<String, Object>) sysRespon.getData();
                        thirdOrderNo = (String) data.get("uuid");
                    }
                    String code = sysRespon.getResponCode();
                    if (com.qujia.common.utils.StringUtils.equalsAny(code,"0000","2002")) {
                        callBackForRefundSuccess(order,refundOrderNo, LocalDateTime.now());
                    }else {
                        sysRespon = null;
                    }
                }
                break;
            case "5":  // 云化支付
                sysRespon = yunhuaRefund(order,refundOrderNo, payWay);
                if (sysRespon != null) {
                    if (sysRespon.getData() != null) {
                        JSONObject data = (JSONObject) sysRespon.getData();
                        thirdOrderNo = data.getString("refundTransInfoNo");
                        thirdPayNo = data.getString("refundTransPayNo");
                    }
                    if (com.qujia.common.utils.StringUtils.equals("0000",sysRespon.getResponCode())) {
                        callBackForRefundSuccess(order,refundOrderNo,LocalDateTime.now());
                    }else{
                        sysRespon = null;
                    }
                }
                break;
            default:
                throw new CustomException("不支持的支付渠道");
        }
        if (sysRespon == null) {
            //callBackForRefundFail(refundRecord,thirdOrderNo,thirdPayNo);
            log.error("退款失败");
            throw new CustomException("退款失败");
        }
    }

    private SysRespon sxfRefund(SuperPayOrder order,String refundOrderNo, PayWay payWay){
        try {
            return payOrderService.sendSxfRefundOrder(order.getAmt(), refundOrderNo, order.getSuperOrderNo(), payWay.getMno());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private SysRespon yunhuaRefund(SuperPayOrder order,String refundOrderNo, PayWay payWay){
        try {
            PayOrder payOrder = new PayOrder();
            payOrder.setAmt(order.getAmt());
            payOrder.setReceivedAmt(order.getAmt());
            payOrder.setOrderNo(order.getSuperOrderNo());
            payOrder.setMerchantsNumber(order.getMerchantsNumber());
            payOrder.setTransactionId(order.getTransactionId());
            payOrder.setPayWayId(payWay.getPayWayId());
            payOrder.setStationId(Long.valueOf(order.getStationId()));
            payOrder.setPayDate(LocalDateUtils.localDateTimeToDate(order.getPayTime()));
            return payOrderService.yunHuaRefundV2(refundOrderNo,payOrder, payWay);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private void callBackForRefundSuccess(SuperPayOrder order,String refundOrderNo, LocalDateTime refundTime){
        log.info("超级会员退款成功回调，orderNo:[{}]，refundOrderNo:{}",order.getSuperOrderNo(),refundOrderNo);
        SuperPayOrder update = new SuperPayOrder();
        update.setSuperPayId(order.getSuperPayId());
        update.setStatus("3");
        update.setRefundTime(refundTime);
        this.updateById(update);
        log.info("超级会员退款成功回调-成功，orderNo:[{}]，refundOrderNo:{}",order.getSuperOrderNo(),refundOrderNo);
    }

}
